package com.sunyur.tailor.channel.service.inner.project.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.sunyur.tailor.channel.common.inner.base.SunyurResult;
import com.sunyur.tailor.channel.common.inner.util.SunyurClientUtil;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import com.sunyur.tailor.channel.service.inner.project.param.BatchSyncProjectParam;
import com.sunyur.tailor.channel.service.inner.project.param.BatchUpdateProjectStatusParam;
import com.sunyur.tailor.channel.service.inner.project.service.SunyurProjectService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.List;

@Service("SunyurProjectService")
public class SunyurProjectServiceImpl implements SunyurProjectService {
    private final static Logger LOGGER_INFO = LoggerFactory.getLogger(SunyurProjectServiceImpl.class);
    private final static Logger LOGGER_ERROR = LoggerFactory.getLogger(SunyurProjectServiceImpl.class);

    /**
     * 请求商越Client
     */
    @Autowired
    private SunyurClientUtil sunyurClient;

    /**
     * 项目同步 链接
     */
    @Value("${sunyur.api.batchSyncProject}")
    private String batchSyncProject;

    /**
     * 修改项目同步 链接
     */
    @Value("${sunyur.api.batchUpdateProjectStatus}")
    private String batchUpdateProjectStatus;

    @Override
    public ChannelResult<Boolean> batchSyncProject(List<BatchSyncProjectParam> batchSyncProjectParam) throws Exception {
        LOGGER_INFO.info("SunyurProjectServiceImpl batchSyncProject batchSyncProjectParam.size is {}， param is {}", batchSyncProjectParam.size(), JSON.toJSONString(batchSyncProjectParam));
        if (CollectionUtils.isEmpty(batchSyncProjectParam)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurProjectServiceImpl batchSyncProject batchSyncProjectParam is null");
        }
        // 参数按长度分割
        List<List<BatchSyncProjectParam>> partition = Lists.partition(batchSyncProjectParam, 20);
        // 返回错误信息结果集
        List<String> errorMsgList = Lists.newArrayList();
        // 循环调用创建或更新供应商接口
        for (int i = 0; i < partition.size(); i++) {
            // 调用主线创建或更新供应商接口
            SunyurResult sunyurResult = sunyurClient.execPost(batchSyncProject, JSON.toJSONString(partition.get(i)), null);
            // 某次调用主线返回错误（本次新增失败，记录错误信息，继续新增下一批）
            if (!"success".equals(sunyurResult.getCode())) {
                LOGGER_ERROR.error("第{}批失败， syncSupplierList loop call sunyur request fail, param is {}, result is {}", i + 1, JSON.toJSONString(partition.get(i)), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add("第" + +i + "批失败，" + sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(Boolean.TRUE);
    }

    @Override
    public ChannelResult<Boolean> batchUpdateProjectStatus(BatchUpdateProjectStatusParam batchUpdateProjectStatusParam) throws Exception {
        LOGGER_INFO.info("batchUpdateProjectStatus batchUpdateProjectStatus param is {}", JSON.toJSONString(batchUpdateProjectStatusParam));
        if (ObjectUtils.isEmpty(batchUpdateProjectStatusParam)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "batchUpdateProjectStatus batchUpdateProjectStatus param is null");
        }
        List<String> projectCodes = batchUpdateProjectStatusParam.getProjectCodes();
        // 参数按长度分割
        List<List<String>> partition = Lists.partition(projectCodes, 20);
        // 返回错误信息结果集
        List<String> errorMsgList = Lists.newArrayList();
        // 循环调用创建或更新供应商接口
        for (int i = 0; i < partition.size(); i++) {
            batchUpdateProjectStatusParam = new BatchUpdateProjectStatusParam();
            batchUpdateProjectStatusParam.setProjectCodes(partition.get(i));
            batchUpdateProjectStatusParam.setStatus(batchUpdateProjectStatusParam.getStatus());
            // 调用主线创建或更新供应商接口
            SunyurResult sunyurResult = sunyurClient.execPost(batchUpdateProjectStatus, JSON.toJSONString(batchUpdateProjectStatusParam), null);
            // 某次调用主线返回错误（本次新增失败，记录错误信息，继续新增下一批）
            if (!"success".equals(sunyurResult.getCode())) {
                LOGGER_ERROR.error("第{}批失败， syncSupplierList loop call sunyur request fail, param is {}, result is {}", i + 1, JSON.toJSONString(partition.get(i)), JSON.toJSONString(sunyurResult));
                // 每批次错误信息收集
                errorMsgList.add("第" + +i + "批失败，" + sunyurResult.getContent() + "-" + sunyurResult.getErrorMessage());
            }
        }
        // 存在错误信息
        if (!CollectionUtils.isEmpty(errorMsgList)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), JSON.toJSONString(errorMsgList));
        }
        return ChannelResultUtil.success(Boolean.TRUE);
    }
}